package com.rzico.sbl.ui.statistic

import android.widget.ImageView
import androidx.core.view.isVisible
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityStockBalanceBinding
import com.rzico.sbl.model.FilterData
import com.rzico.sbl.model.StockBalance
import com.rzico.sbl.other.getBeforeDate
import com.rzico.sbl.other.getBeforeEndDate
import com.rzico.sbl.other.getBeforeFirstDate
import com.rzico.sbl.other.getEndDate
import com.rzico.sbl.other.getFirstDate
import com.rzico.sbl.other.getMondayDate
import com.rzico.sbl.other.getSundayDate
import com.rzico.sbl.other.getTodayDate
import com.rzico.sbl.other.getYearEndDate
import com.rzico.sbl.other.getYearFirstDate
import com.rzico.sbl.viewmodel.StatisticStockViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.conditionFalse
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.gone
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.orEmpty
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter

class StockBalanceActivity : BaseActivity(R.layout.activity_stock_balance) {

    private val mBinding by lazy { ActivityStockBalanceBinding.bind(getRootView()) }

    private val mShopList = arrayListOf<FilterData>()

    private var mShopId = ""
    private var mBeginDate = getFirstDate()
    private var mEndDate = getEndDate()

    override fun getViewModel() = get<StatisticStockViewModel>()

    override fun initData() {
        initTitle(title = "账面结存")

        initLayout()

        getShopList()
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout
                    .emptyHint
                    .text = "暂无相关商品信息！"

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                    mAdapter = SlimAdapter.creator()
                        .register<StockBalance>(R.layout.item_stock_balance) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_stock_name, bean.name)
                                text(R.id.item_stock_code, bean.sn)
                                text(R.id.item_stock_group, bean.category.orEmpty())
                                text(R.id.item_stock_in, bean.credit)
                                text(R.id.item_stock_out, bean.debit)
                                text(R.id.item_stock_start, bean.balance)
                                text(R.id.item_stock_end, bean.stock)

                                with<ImageView>(R.id.item_stock_img) {
                                    it.loadImage(bean.thumbnail)
                                }

                                clicked {
                                    startActivityEx<StockRecordActivity>(
                                        "stockId" to bean.id
                                    )
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    override fun initListener() {
        mBinding
            .apply {
                getViewModel().mUncheckTimeList[3].isChecked = true
                balanceTime.text = getViewModel().mUncheckTimeList[3].hint

                balanceShopLl.oneClick {
                    getViewModel()
                        .showDropFilter(
                            getIContext(),
                            balanceTop,
                            mShopList,
                            balanceShop,
                            balanceShopArrow
                        ) {
                            mShopId = it.id
                            updateList()
                        }
                }

                balanceTimeLl.oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            balanceTime,
                            balanceTimeArrow,
                            balanceTop,
                            getViewModel().mUncheckTimeList
                        ) { bean ->

                            if (bean.id != "7")
                                getViewModel()
                                    .mUncheckTimeList
                                    .last()
                                    .name = "自定义时间"

                            when (bean.id) {
                                "1" -> {
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    updateList()
                                }

                                "2" -> {
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    updateList()
                                }

                                "3" -> {
                                    mBeginDate = getMondayDate()
                                    mEndDate = getSundayDate()

                                    updateList()
                                }

                                "4" -> {
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    updateList()
                                }

                                "5" -> {
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    updateList()
                                }

                                "6" -> {
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    updateList()
                                }

                                "7" -> {
                                    showTimeRangeDialog(
                                        isCurrentDate = true,
                                        isAfterLimited = true,
                                        onResult = { start, end ->
                                            getViewModel()
                                                .mUncheckTimeList
                                                .forEach { it.isChecked = false }

                                            getViewModel()
                                                .mUncheckTimeList
                                                .last()
                                                .isChecked = true

                                            mBeginDate = start
                                            mEndDate = end
                                            bean.name = "$mBeginDate ~ $mEndDate"
                                            balanceTime.text = bean.name

                                            updateList()
                                        }
                                    )
                                }
                            }
                        }
                }
            }
    }

    /**
     * 获取店铺列表，含自提点
     */
    private fun getShopList() {
        getViewModel()
            .shopList { list ->
                mShopList.clear()
                list.notEmpty {
                    mapTo(mShopList) {
                        FilterData(
                            it.shopName.orEmpty(),
                            it.id,
                            it.shopName.orEmpty()
                        )
                    }
                }

                mShopId = mShopList[0].id
                mShopList[0].isChecked = true

                mBinding.apply {
                    balanceShop.text = mShopList[0].name

                    listLayout
                        .swipeRefresh
                        .isRefreshing = true
                }

                getData(pageNum)
            }
    }

    /**
     * 商品结存列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .goodsbalance(
                page = index,
                shopId = mShopId,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it.data)
                        it.data.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}